//
//  ChartView.m
//  Daybook
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 zhangbin. All rights reserved.
//

#import "ChartView.h"
#import "Common.h"

#define PIE_HEIGHT [CalculateFrameView setHeight:280]


@interface ChartView ()<PieChartDelegate>

@property (nonatomic,strong) NSMutableArray *outLayColorArray;
@property (nonatomic,strong) NSMutableArray *incomeColorArray;
@property (nonatomic,strong) UIView *pieContainer;
@property (nonatomic,strong) UILabel *selLabel;
@property (nonatomic, strong) UILabel *nameLabel;

@property (nonatomic, strong)  NSMutableArray *outLayArr;
@property (nonatomic, strong) NSMutableArray *outLayNameArr;

@property (nonatomic, strong) NSMutableArray *incomeArr;
@property (nonatomic, strong) NSMutableArray *incomeNameArr;

@property (nonatomic, strong) UIView *bottomLineView;

@property (nonatomic, strong) UILabel *noRecordLabel;



@end
@implementation ChartView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];

        self.inOut = YES;
        self.outLayArr = [NSMutableArray array];
        self.incomeArr = [NSMutableArray array];
        self.outLayNameArr = [NSMutableArray array];
        self.incomeNameArr = [NSMutableArray array];
        self.outLayColorArray = [NSMutableArray array];
        self.incomeColorArray = [NSMutableArray array];
        self.beginDate = [[CalendarTool shareCalendarTool] firstDayFromDate:[NSDate date]];
        self.endDate = [[CalendarTool shareCalendarTool] lastDayFromDate:[NSDate date]];
        [self createChartView];
        [self refreshData];
    }
    return self;
}

- (void)refreshData {
    if (_inOut) {
        // 支出
        BOOL isdaNull = [[ChartTool shareChartTool] isNullInDataBaseWithBeginDate:_beginDate endDate:_endDate type:@"2"];
        if (isdaNull == YES) {
           // 没有数据
            [self.outLayArr removeAllObjects];
            [self.outLayNameArr removeAllObjects];
            self.outLayColorArray = @[[UIColor lightGrayColor]].mutableCopy;
            self.outLayArr = @[[NSNumber numberWithInt:1]].mutableCopy;
            NSLog(@"执行创建支出没有数据");
        }else {
           // 有数据
            NSArray *outLayArr = [[ChartTool shareChartTool] outLayDictionaryArrayWithBeginDate:_beginDate endDate:_endDate];
            [self.outLayArr removeAllObjects];
            [self.outLayNameArr removeAllObjects];
            for (NSDictionary *dic in outLayArr) {
                [self.outLayArr addObject:dic[@"money"]];
                [self.outLayNameArr addObject:dic[@"name"]];
            }
            self.outLayColorArray = [ChartPicColor payColorArrByNameArr:_outLayNameArr];
            NSLog(@"执行创建支出有数据");

        }

    }else {
        // 收入
        BOOL isdaNull = [[ChartTool shareChartTool] isNullInDataBaseWithBeginDate:_beginDate endDate:_endDate type:@"1"];
        if (isdaNull == YES) {
            // 没有数据
            [self.incomeArr removeAllObjects];
            [self.incomeNameArr removeAllObjects];
            self.incomeColorArray = @[[UIColor lightGrayColor]].mutableCopy;
            self.incomeArr = @[[NSNumber numberWithInt:1]].mutableCopy;
            NSLog(@"执行创建收入没有数据");
        }else {
            // 有数据
            NSArray *incomeArr = [[ChartTool shareChartTool] incomeDictionaryArrayWithBeginDate:_beginDate endDate:_endDate];
            [self.incomeArr removeAllObjects];
            [self.incomeNameArr removeAllObjects];
            for (NSDictionary *dic in incomeArr) {
                [self.incomeArr addObject:dic[@"money"]];
                [self.incomeNameArr addObject:dic[@"name"]];
            }
            self.incomeColorArray = [ChartPicColor incomeColorArrByNameArr:_incomeNameArr];
            NSLog(@"执行创建收入有数据");
        }
    }

    [self refreshChartView];
}

- (void)refreshChartView {
//    NSLog(@"outframe: %@", _pieChartView);

    self.pieChartView.delegate = nil;
    [self.pieChartView removeFromSuperview];
    
//    NSLog(@"ountcoleorBefore: %@", _outLayColorArray);
//    NSLog(@"pieContainerBefore: %@", _pieContainer);

    self.pieChartView = [[PieChartView alloc]initWithFrame:self.pieContainer.bounds withValue:self.inOut?_outLayArr:_incomeArr withColor:self.inOut?_outLayColorArray:_incomeColorArray];
    self.pieChartView.delegate = self;
    [self.pieContainer addSubview:self.pieChartView];
    
    
//    NSLog(@"ountcoleorAfter: %@", _outLayColorArray);
//    for (NSString *str in _outLayNameArr) {
//        NSLog(@"outNameArr: %@", str);
//    }
//    NSLog(@"outframeEnd: %@", _pieChartView);
//    NSLog(@"pieContainerEnd: %@", _pieContainer);

    [self.pieChartView reloadChart];
    

    
    if (_inOut) {
        [self.pieChartView setTitleText:@"支出总计"];
        [self.pieChartView setAmountText:[NSString stringWithFormat:@"-%@", [ChartTool totalOutLayWithBeginDate:_beginDate endDate:_endDate]]];
    }else {
        [self.pieChartView setTitleText:@"收入总计"];
        [self.pieChartView setAmountText:[NSString stringWithFormat:@"+%@", [ChartTool totalIncomeWithBeginDate:_beginDate endDate:_endDate]]];
    }
}


- (void)createChartView
{

    
    //add shadow img
    CGRect pieFrame = CGRectMake((self.frame.size.width - PIE_HEIGHT) / 2, 0, PIE_HEIGHT, PIE_HEIGHT);
    
    UIImage *shadowImg = [UIImage imageNamed:@""];
    UIImageView *shadowImgView = [[UIImageView alloc]initWithImage:shadowImg];
    shadowImgView.frame = CGRectMake(0, pieFrame.origin.y + PIE_HEIGHT*0.92, shadowImg.size.width/2, shadowImg.size.height/2);
    [self addSubview:shadowImgView];
    
    self.pieContainer = [[UIView alloc]initWithFrame:pieFrame];
//    self.pieChartView = [[PieChartView alloc]initWithFrame:self.pieContainer.bounds withValue:_outLayArr withColor:_outLayColorArray];
//    self.pieChartView.delegate = self;
//    [self.pieContainer addSubview:self.pieChartView];
//    [self.pieChartView setAmountText:[NSString stringWithFormat:@"-%@", [ChartTool totalOutLayWithBeginDate:_beginDate endDate:_endDate]]];
    [self addSubview:self.pieContainer];
    
    //add selected view
    UIImageView *selView = [[UIImageView alloc]init];
//    selView.image = [UIImage imageNamed:@"upLineGray.png"];
    selView.frame = CGRectMake(0, [CalculateFrameView setHeight:280], 2, [CalculateFrameView setHeight:35]);
    selView.backgroundColor = [UIColor lightGrayColor];
    selView.center = CGPointMake([CalculateFrameView setWidth:207.5] , [CalculateFrameView setHeight:300]);
    [self addSubview:selView];
    
    self.selLabel = [[UILabel alloc]initWithFrame:CGRectMake([CalculateFrameView setWidth:225], [CalculateFrameView setHeight:325], [CalculateFrameView setWidth:100], [CalculateFrameView setHeight:23])];
    self.selLabel.backgroundColor = [UIColor clearColor];
    self.selLabel.textAlignment = NSTextAlignmentLeft;
    self.selLabel.font = [UIFont systemFontOfSize:17];
    self.selLabel.textColor = [UIColor blackColor];
    [self addSubview:self.selLabel];
    [self.pieChartView setTitleText:@"支出总计"];
    
    self.nameLabel = ({
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake([CalculateFrameView setWidth:90], [CalculateFrameView setHeight:325], [CalculateFrameView setWidth:100], [CalculateFrameView setHeight:23])];
        [self addSubview:tempLabel];
        tempLabel.textAlignment = NSTextAlignmentRight;
//        tempLabel.backgroundColor = [UIColor blueColor];
        tempLabel;
    });
    
    self.noRecordLabel = ({
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [CalculateFrameView setWidth:200], [CalculateFrameView setHeight:23])];
        tempLabel.center = CGPointMake(MAIN_WIDTH / 2, [CalculateFrameView setHeight:336.5]);
        [self addSubview:tempLabel];
        tempLabel.textAlignment = NSTextAlignmentCenter;
//        tempLabel.backgroundColor = [UIColor yellowColor];
        tempLabel;
    });
    
    self.bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 1 , MAIN_WIDTH, 1)];
    [self addSubview:_bottomLineView];
    _bottomLineView.backgroundColor = LINE_COLOR;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshChartAction) name:@"refreshChartAction" object:nil];
    
}

- (void)refreshChartAction {
     [self refreshData];
//    NSLog(@"ountcoleorAfter: %@", _outLayColorArray);
//    for (NSString *str in _outLayNameArr) {
//        NSLog(@"outNameArr: %@", str);
//    }
//    NSLog(@"outframeEnd: %@", _pieChartView);
//
//    [self.pieChartView reloadChart];
}

- (UIColor *) colorFromHexRGB:(NSString *) inColorString
{
    UIColor *result = nil;
    unsigned int colorCode = 0;
    unsigned char redByte, greenByte, blueByte;
    
    if (nil != inColorString)
    {
        NSScanner *scanner = [NSScanner scannerWithString:inColorString];
        (void) [scanner scanHexInt:&colorCode]; // ignore error
    }
    redByte = (unsigned char) (colorCode >> 16);
    greenByte = (unsigned char) (colorCode >> 8);
    blueByte = (unsigned char) (colorCode); // masks off high bits
    result = [UIColor
              colorWithRed: (float)redByte / 0xff
              green: (float)greenByte/ 0xff
              blue: (float)blueByte / 0xff
              alpha:1.0];
    return result;
}

- (void)selectedFinish:(PieChartView *)pieChartView index:(NSInteger)index percent:(float)per
{
    if (self.inOut) {
        if (_outLayNameArr.count == 0) {
            self.noRecordLabel.text = @"暂时没有数据";
            self.noRecordLabel.hidden = NO;
            self.selLabel.hidden = YES;
            self.nameLabel.hidden = YES;
        }else {
            self.selLabel.text = [NSString stringWithFormat:@"%2.2f%@",per*100,@"%"];
            self.noRecordLabel.hidden = YES;
            self.selLabel.hidden = NO;
            self.nameLabel.hidden = NO;
            self.nameLabel.text = _outLayNameArr[index];
        }
    }else {
        if (_incomeNameArr.count == 0) {
            self.noRecordLabel.text = @"暂时没有数据";
            self.noRecordLabel.hidden = NO;
            self.selLabel.hidden = YES;
            self.nameLabel.hidden = YES;
        }else {
            self.selLabel.text = [NSString stringWithFormat:@"%2.2f%@",per*100,@"%"];
            self.nameLabel.text = _incomeNameArr[index];
            self.noRecordLabel.hidden = YES;
            self.selLabel.hidden = NO;
            self.nameLabel.hidden = NO;
        }
    }
}

- (void)onCenterClick:(PieChartView *)pieChartView
{
//    self.inOut = !self.inOut;
//    [self refreshData];
//    [self.delegate isIncomeTure:!_inOut];
}




@end
